# -*- coding: utf-8 -*-
# @Time     : 2023/12/8 2:13
# @Author   : JustFly
# @File     : server_demo.py
# @Software : PyCharm


import botpy
from botpy.types.message import Message
from botpy.message import DirectMessage
import requests
import re
from botpy import logger
from common.scripts import get_datetime
from config.bot import APP_ID, CLIENT_SECRET, ACCESS_TOKEN_FILE

# 读取TOKEN
with open(ACCESS_TOKEN_FILE, 'r') as file:
    ACCESS_TOKEN = file.read()
    logger.info(f"【{get_datetime.func()}】读取到ACCESS_TOKEN: {ACCESS_TOKEN}")


class MyClient(botpy.Client):
    async def on_at_message_create(self, message: Message):
        msg = re.sub(r'<@!\d+>', "", message.content)
        logger.info(f"【{get_datetime.func()}】频道({message.channel_id})成员【{message.member.nick}】发来一条@消息：{msg}")
        reply_msg = msg if msg != "" else "艾特俺干啥？"
        await self.api.post_message(channel_id=message.channel_id, content=reply_msg)
        # 回复消息
        # url = f'https://api.sandbox.qq.com/channels/{message.channel_id}/messages'
        # headers = {'Content-Type': 'application/json',
        #            'Authorization': "QQBot " + ACCESS_TOKEN,
        #            'X-Union-Appid': APP_ID}
        #
        # data = {
        #     "content": reply_msg,
        #     "msg_type": 0
        # }
        #
        # response = requests.post(url, json=data, headers=headers)
        # if response.status_code == 200:
        #     # 请求成功
        #     print("请求成功")
        #     print(response.json())  # 如果响应是JSON格式的，请使用response.json()来获取数据
        # else:
        #     # 请求失败
        #     print(f"请求失败，状态码: {response.status_code}")
        #     print(response.text)  # 打印错误信息

    async def on_direct_message_create(self, message: DirectMessage):
        print(f"收到了【{message.author.username}】的私信消息 ！")
        # await self.api.post_message(channel_id=message.channel_id, content="content")
        # 回复消息
        # 频道私信
        url = f'https://sandbox.api.sgroup.qq.com/v2/users/{message.author.id}/messages'
        # 频道群聊
        # url = f'https://api.sgroup.qq.com/channels/{message.channel_id}/messages'
        headers = {'Authorization': "QQBot " + ACCESS_TOKEN,
                   'X-Union-Appid': APP_ID}

        data = {
            "content": "hello",
            "msg_type": 0
        }

        response = requests.post(url, json=data, headers=headers)
        if response.status_code == 200:
            # 请求成功
            print("请求成功")
            print(response.json())  # 如果响应是JSON格式的，请使用response.json()来获取数据
        else:
            # 请求失败
            print(f"请求失败，状态码: {response.status_code}")
            print(response.text)  # 打印错误信息


# 监听频道 群聊+私聊
intents = botpy.Intents.none()
intents.public_guild_messages = True
intents.direct_message = True

client = MyClient(intents=intents)
client.run(appid=APP_ID, secret=CLIENT_SECRET)
